package com.android.test.download;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Downloader {

	void p(String s) {
		System.out.println(s);
	}

	private boolean isCancel = false;
	private int completedSize = 0;

	public boolean download(String httpUrl, String path) {
		HttpURLConnection conn = null;
		InputStream is = null;
		RandomAccessFile raf = null;
		try {
			isCancel = false;
			File file = new File(path);
			raf = new RandomAccessFile(file, "rw");

			URL url = new URL(httpUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(10 * 1000);
			conn.setRequestProperty("User-Agent", "NetFox");
			if (completedSize > 0) {
				conn.setRequestProperty("Range", String.format("bytes=%s-", completedSize));
				raf.seek(completedSize);
			}

			is = conn.getInputStream();
			int contentLength = conn.getContentLength();
			if (onDownloadListener != null)
				onDownloadListener.onContentLength(contentLength);
			byte[] buffer = new byte[1024 * 10];
			int byteCount = 0;
			while (!isCancel && (byteCount = is.read(buffer)) != -1) {
				raf.write(buffer, 0, byteCount);
				completedSize += byteCount;
				if (onDownloadListener != null)
					onDownloadListener.onProgressChanage(completedSize);
			}
			if (completedSize == contentLength) {
				completedSize = 0;
			}
			return true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
				raf.close();
				conn.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return false;
	}

	public void cancel(boolean cancel) {
		isCancel = cancel;
	}

	public boolean isCancel() {
		return isCancel;
	}

	private OnDownloadListener onDownloadListener;

	public void setOnDownloadListener(OnDownloadListener onDownloadListener) {
		this.onDownloadListener = onDownloadListener;
	}

	public interface OnDownloadListener {
		public void onContentLength(int length);

		public void onProgressChanage(int completedSize);
	}
}
